<?php
/**
 * Created by PhpStorm.
 * User: 雨寒
 * Date: 2018/8/17
 * Time: 下午5:21
 */

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Loader;

class News extends Common
{

    /**
     *获取快讯的类别
     * @return array
     **/
    static public function getType(){
        $type = Config('news_type');
        foreach ($type as $key=>$item){
            $type[$key]['_id'] = $item['type'];
            $type[$key]['title'] = $item['type_name'];
            unset($type[$key]['type']);
            unset($type[$key]['type_name']);
            unset($type[$key]['color']);
        }
        return empty($type)?[]:array_values($type);
    }

    /**
     *获取快讯列表
     * @param string $type 快讯类别
     * @param string $page 第几页
     * @param string $page_size 一页几条
     * @param string $time 比较时间标准
     **/
    static public function newsList($type=0,$page=1,$page_size=10,$time=0){
        $where = [
            'is_pass'=>1,
        ];
        if(!empty($type)){
            $where['type'] = $type;
        }

        $list = Db::name('news')
            ->where($where)
            ->order('id DESC')
            ->field('detail,img_url,end_time,leave_sugar,goods_id,create_time,id as _id')
            ->page($page,$page_size)
            ->select();

        foreach ($list as $key=>$item){

            $date_time = strtotime(date('Y-m-d',$item['create_time']));

            if($date_time!=$time){
                $list[$key]['add'] = 1;
                $list[$key]['date'] = newsTime($item['create_time']);
            }else{
                $list[$key]['add'] = 0;
                $list[$key]['date'] = '';
            }

            $time = $date_time;

            $list[$key]['create_time'] = date('H:i',$item['create_time']);
            if($item['end_time']<time()||$item['leave_sugar']<=0){
                $list[$key]['end_time'] = '';
                $list[$key]['leave_sugar'] = '';
            }else{
                $list[$key]['end_time'] = timeCountDown($item['end_time']);
            }

        }
        $arr['data'] = empty($list)?[]:$list;
        $arr['time'] = $time;
        return $arr;
    }

    /**
     * 我发布的
     * @param $user_id
     * @param int $page
     * @param int $page_size
     * @return mixed
     */
    static public function newsMine($user_id,$page=1,$page_size=10){
        $where = [
            'type'=>3,
            'uid'=>$user_id
        ];
        $list = Db::name('news')
            ->where($where)
            ->order('id DESC')
            ->field('detail,img_url,is_pass,create_time,id as _id')
            ->page($page,$page_size)
            ->select();

        foreach ($list as &$item){
            $item['date'] = accurateDate($item['create_time']).' 提交';
            if($item['is_pass']==1){
                $item['is_pass'] = '已审核';
            }else{
                $item['is_pass'] = '待审核';
            }
            unset($item['create_time']);
            $item['add'] = 1;
        }

        $arr['data'] = empty($list)?[]:$list;
        return $arr;
    }

    /**
     * 快讯会员发布限制
     * @param $user
     * @return array
     */
    static public function newsSubInfo($user){
        $rate = Settings::getRate();
        $arr = [
            'my_sugar'=>$user['sugar'],
            'publish_low_sugar'=>$rate['publish_low_sugar'],
            'publish_high_font'=>$rate['publish_high_font'],
            'publish_desc_font'=>$rate['publish_desc_font'],
        ];
        return $arr;
    }

    /**
     * 发布快讯
     * @param $user
     * @param $content
     * @param $img_url
     * @param $sugar
     * @param $desc
     * @return array
     * @throws ServerException
     * @throws UserException
     */
    static public function newsSub($user,$content,$img_url,$sugar,$desc){
        $rate = Settings::getRate();
        $global = Settings::getSettings(H_SETTINGS_GLOBAL,2);
        $content = remove_all_tags2($content);
        $desc = remove_all_tags($desc);
        if(empty($content)){
            throw new UserException('请输入快讯内容');
        }
        if(empty($desc)){
            throw new UserException('请输入快讯简介');
        }
        $length = mb_strlen($content,'UTF8');
        if($length>$rate['publish_high_font']){
            throw new UserException('快讯内容最多输入'.$rate['publish_high_font'].'字符！');
        }
        $length2 = mb_strlen($desc,'UTF8');
        if($length2>$rate['publish_desc_font']){
            throw new UserException('快讯简介最多输入'.$rate['publish_desc_font'].'字符！');
        }
        $sugar = intval($sugar);

        if($sugar>$user['sugar']){
            throw new UserException('您的'.$global['sugar']['title'].'余额不足！');
        }
        if($sugar>$user['sugar']){
            throw new UserException('您的'.$global['sugar']['title'].'余额不足！');
        }
        if($rate['publish_low_sugar']>0 && $rate['publish_low_sugar']>$sugar){
            throw new UserException($global['sugar']['title'].'最少为'.$rate['publish_low_sugar']);
        }

        $end_time = now_datetime()+config('news_share_end_time')*3600;
        $data = [
            'type'=>3,
            'uid'=>$user['id'],
            'detail'=>$content,
            'desc'=>$desc,
            'img_url'=>$img_url,
            'end_time'=>$end_time,
            'all_sugar'=>$sugar,
            'leave_sugar'=>$sugar,
            'create_time'=>now_datetime(),
            'update_time'=>now_datetime(),
        ];

        $id = Db::name('news')->insertGetId($data);

        if(!$id){
            throw new ServerException('快讯保存失败');
        }

        if($sugar>0){
            User::addDelSugar($user['id'],'4',$id,-$sugar,'会员身份发布快讯',$data['create_time']);
        }

        return [
            'cut_sugar'=>'-'.$sugar,
            'str'=>'已发布'
        ];

    }

    /**
     * 分享成功
     * @param $user
     * @param $id
     * @return array
     * @throws UserException
     */
    static public function newsSharesSuccess($user,$id){
        $info = Db::name('news')->where('id',$id)->find();
        $rate = Settings::getRate();
        $global = Settings::getSettings(H_SETTINGS_GLOBAL,2);

        $share_one_max = $rate['share_one_max'];//每篇限制
        $share_day_max = $rate['share_day_max'];//每日限制
        $share_news_award_low = $rate['share_news_award_low'];//最低奖励
        $share_news_award_high = $rate['share_news_award_high'];//最高奖励

        $status = 0;//是否显示糖果框
        $sugar = 0;//加多少糖果
        $str = '';//显示字符
        $up_status = 0;//显示升级按钮吗

        if($info){
            if($info['leave_sugar']>0 && $info['end_time']>time() && $info['is_pass']==1){
                //未到期 有剩余糖果
                $count = Db::name('user_shares_log')->where(['uid'=>$user['id'],'type'=>1,'news_id'=>$id,'sugar'=>['gt',0]])->count();
                if($count>=$share_one_max){
                    //每篇分享达到限制
                }else{
                    $beginToday = getBeginToday();
                    $endToday = getEndToday();
                    $map = [
                        'uid'=>$user['id'],
                        'sugar'=>['gt',0],
                        'type'=>1,
                        'create_time'=>['between',[$beginToday,$endToday]]
                    ];
                    $count2 = Db::name('user_shares_log')->where($map)->count();
                    if($count2>=$share_day_max){
                        //达到每日限制
                    }else{
                        $sugar = rand($share_news_award_low,$share_news_award_high);
                        if($sugar>0){
                            $status=1;
                            $str = '今日分享收益次数'.++$count2;
                            if($user['identity']==1&&$rate['can_visitor_half']==1){
                                //游客  奖励减半开启
                                $sugar = intval($sugar/2);
                                if($sugar<1){
                                    $sugar=1;
                                }
                                $str = '游客+'.$sugar.'（VIP+'.($sugar*2).'）';
                                $up_status = 1;
                            }
                            if($sugar>$info['leave_sugar']){
                                $sugar=$info['leave_sugar'];
                            }
                        }
                    }
                }
            }
            $change = [
                'shares'=>$info['shares']+1,
                'leave_sugar'=>$info['leave_sugar']-$sugar
            ];
            Db::name('news')->where('id',$id)->update($change);

            $data = [
                'uid'=>$user['id'],
                'news_id'=>$id,
                'sugar'=>$sugar,
                'create_time'=>now_datetime()
            ];

            $log_id = Db::name('user_shares_log')->insertGetId($data);

            if($sugar>0){
                User::addDelSugar($user['id'],4,$log_id,$sugar,'分享快讯奖励','',$option=1);
            }

        }

        //广告
        $ad_status = 0;
        $ad_img = '';
        $ad_type = '';
        $ad_url = '';
        if($status==1){
            $ad = Db::name('news_advert')
                ->where('id',1)
                ->where('is_visible',1)
                ->field('img_url,type,link_url')
                ->find();
            if($ad){
                $ad_status = 1;
                $ad_img = $ad['img_url'];
                $ad_type = $ad['type'];
                $ad_url = $ad['link_url'];
            }
        }

        $arr = [
            'status'=>$status,
            'sugar' => '+'.$sugar,
            'str'=>$str,
            'up_status'=>$up_status,
            'up_title'=>$global['how_vip_title'],
            'up_url'=>$global['how_vip_url'],
            'ad_status'=>$ad_status,
            'ad_img'=>$ad_img,
            'type'=>$ad_type,
            'link_url'=>$ad_url
        ];
        return $arr;
    }

    /**
     * 分享商品成功
     * @param $user
     * @param $id 商品id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    static public function goodsSharesSuccess($user,$id){
        $info = Db::name('goods')->where('id',$id)->find();
        $rate = Settings::getRate();
        $global = Settings::getSettings(H_SETTINGS_GLOBAL,2);

        $share_one_max = $rate['share_one_max'];//每篇限制
        $share_day_max = $rate['share_day_max'];//每日限制
        $share_news_award_low = $rate['share_news_award_low'];//最低奖励
        $share_news_award_high = $rate['share_news_award_high'];//最高奖励

        $status = 0;//是否显示糖果框
        $sugar = 0;//加多少糖果
        $str = '';//显示字符
        $up_status = 0;//显示升级按钮吗

        if($info){
            if($info['leave_sugar']>0 && $info['is_pass']==1 && $info['status']==1){
                //有剩余糖果
                $count = Db::name('user_shares_log')->where(['uid'=>$user['id'],'news_id'=>$id,'type'=>2,'sugar'=>['gt',0]])->count();
                if($count>=$share_one_max){
                    //每篇分享达到限制
                }else{
                    $beginToday = getBeginToday();
                    $endToday = getEndToday();
                    $map = [
                        'uid'=>$user['id'],
                        'type'=>2,
                        'sugar'=>['gt',0],
                        'create_time'=>['between',[$beginToday,$endToday]]
                    ];
                    $count2 = Db::name('user_shares_log')->where($map)->count();
                    if($count2>=$share_day_max){
                        //达到每日限制
                    }else{
                        $sugar = rand($share_news_award_low,$share_news_award_high);
                        if($sugar>0){
                            $status=1;
                            $str = '今日分享收益次数'.++$count2;
                            if($sugar>$info['leave_sugar']){
                                $sugar=$info['leave_sugar'];
                            }
                        }
                    }
                }
            }
            $change = [
                'shares'=>$info['shares']+1,
                'leave_sugar'=>$info['leave_sugar']-$sugar
            ];
            Db::name('goods')->where('id',$id)->update($change);

            $data = [
                'uid'=>$user['id'],
                'type'=>2,
                'news_id'=>$id,
                'sugar'=>$sugar,
                'create_time'=>now_datetime()
            ];

            $log_id = Db::name('user_shares_log')->insertGetId($data);

            if($sugar>0){
                User::addDelSugar($user['id'],7,$log_id,$sugar,'分享商品奖励','',$option=1);
            }

        }

        //广告
        $ad_status = 0;
        $ad_img = '';
        $ad_type = '';
        $ad_url = '';
        if($status==1){
            $ad = Db::name('news_advert')
                ->where('id',1)
                ->where('is_visible',1)
                ->field('img_url,type,link_url')
                ->find();
            if($ad){
                $ad_status = 1;
                $ad_img = $ad['img_url'];
                $ad_type = $ad['type'];
                $ad_url = $ad['link_url'];
            }
        }

        $arr = [
            'status'=>$status,
            'sugar' => '+'.$sugar,
            'str'=>$str,
            'up_status'=>$up_status,
            'up_title'=>'',
            'up_url'=>'',
            'ad_status'=>$ad_status,
            'ad_img'=>$ad_img,
            'type'=>$ad_type,
            'link_url'=>$ad_url
        ];
        return $arr;
    }
    /**
     * 获取分享海报
     * @param $user
     * @param $id
     * @return array
     * @throws UserException
     */
    static public function newsShare($user,$id){
        $info = Db::name('news')->where('id',$id)->field('desc,img_url,goods_id,type,create_time')->find();
        if(!$info){
            throw new UserException('此快讯已删除，请刷新！');
        }
        $week = ['日','一','二','三','四','五','六'];
        $news_time = '星期'.$week[date('w',$info['create_time'])].' '.date('Y/m/d H:i:s',$info['create_time']);

        $publish_desc_font = Settings::getRate('publish_desc_font');

        $detail = remove_all_tags($info['desc']);
        $detail = mb_substr($detail,0,$publish_desc_font,'utf-8');
        /*商家海报单独处理*/
        if($info['type']==2)
        {
            $goods_info= Db::name('goods')->where('id',$info['goods_id'])->field('id,business_id,title,img_url,price,original_price,add_percentage')->find();
            $news_poster = self::goodsPoster($user,$goods_info,$news_time,$info);
        }else{
            $news_poster = self::newsPoster($user,$id,$detail,$info['img_url'],$news_time);
        }

        return [
            'img_url'=>$news_poster
        ];
    }
    /**
     * 获取商品海报
     * @param $user
     * @param $id
     * @return array
     * @throws UserException
     */
    static public function goodsShare($user,$id){
        $goods_info= Db::name('goods')->where('id',$id)->field('id,business_id,title,img_url,price,original_price,add_percentage')->find();
        if(!$goods_info){
            throw new UserException('不存在此商品，请刷新！');
        }
        $week = ['日','一','二','三','四','五','六'];
        $news_time = '星期'.$week[date('w',time())].' '.date('Y/m/d H:i:s',time());
        /*商家海报单独处理*/
        $goods_poster = self::goodsPoster($user,$goods_info,$news_time);
        return [
            'img_url'=>$goods_poster
        ];
    }
    /**
     * 生成快讯海报
     * @param $user
     * @param $id
     * @param $text
     * @param $newsImg
     * @param $newsTime
     * @return string
     * @throws ServerException
     */
    static public function newsPoster($user,$id,$text,$newsImg,$newsTime){
        set_time_limit(0);
        @ini_set('memory_limit', '256M');
        mb_internal_encoding("UTF-8"); // 设置编码

        $type = 7;//当前第几次换样式  换一次加一 防止缓存

        $fullPath = config("public_path") . '/' . config("poster_path").'/newsPoster';
        //创建路径
        self::createDir($fullPath);

        $fileName = md5('u'.$user['id'].'n'.$id.$text.$newsImg.$type).'.png';
        $fullName = $fullPath.'/'.$fileName;
        if (!is_file($fullName))
        {
            $top = config("public_path").'/top.png';
            $top = imagecreatefrompng($top);

            $width = imagesx($top);
            $height = imagesy($top);//画布高度
            $height_top = imagesy($top);

            //字体
            $font = config("public_path") . '/' . "/static/fonts/FZKTJW.TTF";
            $font_size = 32;

            //文字宽度
            $width_font = 570;
            $arr = self::autowrap($font_size, 0, $font, $text, $width_font); // 自动换行处理

            $text = $arr['content'];

            $num = $arr['num'];

            $height_white = intval(($num+2)*50.1);

            $height	+= $height_white;

            $catch_news_img = false;
            if(!empty($newsImg)){
                $newsImg = get_whole_image($newsImg);
                $catch_news_img = true;
                //获取文件内容
                $content_news = file_get_contents($newsImg);
                if($content_news){
                    //根据图片内容创建图片资源
                    $newsImg = imagecreatefromstring($content_news);
                }else{
                    $catch_news_img = false;
                }
                if($catch_news_img){
                    $width_news = imagesx($newsImg);
                    $height_news = imagesy($newsImg);
                    $width_news_now = $width_font;
                    $height_news_now = intval($height_news*$width_font/$width_news);

                    $height_news_y = $height;
                    $height_white += $height_news_now;
                    $height += $height_news_now;
                }
            }

            //底部
            $foot = config("public_path").'/foot.png';
            $foot = imagecreatefrompng($foot);
            $width_foot = imagesx($foot);
            $height_foot = imagesy($foot);
            $height_foot_y = $height;
            $height += $height_foot;

            //二维码
            $qr = self::getUserQr($user);
            $qr = get_whole_image($qr);
            $qr = imagecreatefrompng($qr);
            $width_qr = imagesx($qr);
            $height_qr = imagesx($qr);
            $width_qr_now = 200;
            $height_qr_now = $width_qr_now;

            //logo
            $logo = config("public_path").'/static/images/default_logo.png';
            $logo = imagecreatefrompng($logo);
            $width_logo = imagesx($logo);
            $height_logo = imagesy($logo);
            $width_logo_now = 60;
            $height_logo_now = $width_logo_now;

            // 创建画布
            $bg = imagecreatetruecolor($width, $height);
            $color = imagecolorallocatealpha($bg , 255 , 255 , 255 , 127);//白色
            imagefill($bg,0,0,$color);//填充画布

            //合并头部
            imagecopyresized($bg, $top, 0, 0, 0, 0,$width,$height_top, $width, $height_top);

            //填充白色
            $bg_white = imagecreatetruecolor($width, $height_white);
            $color_white = imagecolorAllocate($bg_white , 255 , 255 , 255);//白色
            imagefill($bg_white,0,0,$color_white);//填充画布
            imagecopyresized($bg, $bg_white, 0, $height_top, 0, 0,$width,$height_white, $width, $height_white);

            $xone = intval(($width-$width_font)/2);

            if($catch_news_img){
                //快讯若有图片合并
                imagecopyresized($bg, $newsImg, $xone, $height_news_y, 0, 0,$width_news_now, $height_news_now, $width_news,$height_news);
            }

            //合并底部
            imagecopyresized($bg, $foot, 0, $height_foot_y, 0, 0,$width_foot,$height_foot, $width_foot, $height_foot);

            //底部贴上二维码
            imagecopyresized($bg, $qr, $xone, $height_foot_y+$xone, 0, 0,$width_qr_now, $height_qr_now, $width_qr,$height_qr);

            //底部贴上logo
            imagecopyresized($bg, $logo, $xone+(($width_qr_now-$width_logo_now)/2), $height_foot_y+$xone+(($width_qr_now-$width_logo_now)/2), 0, 0,$width_logo_now, $height_logo_now, $width_logo,$height_logo);

            //填充文字内容
            $black = imagecolorallocate($bg, 0, 0, 0); // 创建黑色字体
            imagettftext($bg, $font_size, 0, $xone, $height_top+$font_size+10, $black, $font, $text);

            //填充发布时间
            $gray = imagecolorallocate($bg, 161, 161, 161); // 创建灰色字体
            imagettftext($bg, 24, 0, 100, $height_top-26, $gray, $font, $newsTime);

            $finWidth = imagesx($bg);
            $finHeight = imagesy($bg);
            $percent = '0.7';
            //压缩

            $newbg = imagecreatetruecolor($finWidth*$percent, $finHeight*$percent);
            $colornew = imagecolorallocatealpha($bg , 255 , 255 , 255 , 127);//白色
            imagefill($newbg,0,0,$colornew);//填充画布

            imagecopyresampled($newbg,$bg,0,0,0,0,$finWidth*$percent,$finHeight*$percent,$finWidth,$finHeight);

            imagedestroy($bg);

            imagepng($newbg,$fullName);

            imagedestroy($newbg);
        }


        return get_whole_image(config("poster_path").'/newsPoster/'.$fileName);
    }

    /**
     * 商品海报
     * @param $user 用户
     * @param $goods_info 商品信息
     * @param $news_time 发布的时间
     * @param array $newsinfo 快讯信息（单独分享商品的时候不传）
     * @return string
     * @throws ServerException
     */
    static public function goodsPoster($user ,$goods_info, $news_time,$newsinfo=array())
    {
        set_time_limit(0);
        @ini_set('memory_limit', '256M');
        mb_internal_encoding("UTF-8"); // 设置编码

        $business = Db::name('business')->where('id',$goods_info['business_id'])->field('id,type,percentage,add_percentage')->find();
        $rate = Db::name('rate')->where('id',1)->field('normal_self,private_self')->find();
        if(!$business){
            throw new UserException('商品所属商家已闭店');
        }

        if($business['type']==config('direct_type')){
            //工厂店
            $zijizhuan = round($goods_info['price']*$rate['private_self']/100*$business['percentage']/100,4);
        }else{
            //普通
            $zijizhuan = round($goods_info['price']*$rate['normal_self']/100*$business['percentage']/100,4);
        }

        if($goods_info['add_percentage']>0){
            $addtext = '+分红'.$goods_info['add_percentage'].'%';
            if($business['type']==config('direct_type')){
                //工厂店
                $jiazhuan = round($goods_info['price']*$rate['private_self']/100*($business['percentage']+$goods_info['add_percentage'])/100,4);
            }else{
                //普通
                $jiazhuan = round($goods_info['price']*$rate['normal_self']/100*($business['percentage']+$goods_info['add_percentage'])/100,4);
            }
        }else{
            $addtext = '';
            $jiazhuan = '';
        }

        $type = 32;//当前第几次换样式  换一次加一 防止缓存
        $fullPath = config("public_path") . '/' . config("poster_path").'/newsPoster';
        //创建路径
        self::createDir($fullPath);
        if(empty($newsinfo))
        {
            $newsImg=$goods_info['img_url'];
        }else{
            $newsImg=$newsinfo['img_url'];
        }

        //影响图片不同的信息组成文件名
        $fileName = md5('u'.$user['id'].'g'.$goods_info['id'].$newsImg.$business['type'].$business['percentage'].$business['add_percentage'].$rate['normal_self'].$rate['private_self'].$type).'.png';
        $fullName = $fullPath.'/'.$fileName;
        if (!is_file($fullName))
        {
            $top = config("public_path").'/goodstop.png';
            $top = imagecreatefrompng($top);

            $width = imagesx($top);
            $height = imagesy($top);//画布高度
            $height_top = imagesy($top);

            //字体
            $font = config("public_path") . '/' . "/static/fonts/FZKTJW.TTF";
            $font_size = 32;

            //文字宽度
            $width_font = 570;
            /*处理字数*/
            $arr = self::autowrap($font_size, 0, $font, $goods_info['title'], $width_font); // 自动换行处理

            $text = $arr['content'];

            $num = $arr['num'];

            $height_white = intval(($num+2)*50.1);

            $height	+= $height_white;

            $catch_news_img = false;
            if(!empty($newsImg)){
                $newsImg = get_whole_image($newsImg);
                $catch_news_img = true;
                //获取文件内容
                $content_news = file_get_contents($newsImg);
                if($content_news){
                    //根据图片内容创建图片资源
                    $newsImg = imagecreatefromstring($content_news);
                }else{
                    $catch_news_img = false;
                }
                if($catch_news_img){
                    $width_news = imagesx($newsImg);
                    $height_news = imagesy($newsImg);
                    $width_news_now = $width_font;
                    $height_news_now = intval($height_news*$width_font/$width_news);

                    $height_news_y = $height;
                    $height_white += $height_news_now;
                    $height += $height_news_now;
                }
            }

            //底部
            $foot = config("public_path").'/goodsfoot.png';
            $foot = imagecreatefrompng($foot);
            $width_foot = imagesx($foot);
            $height_foot = imagesy($foot);
            $height_foot_y = $height;
            $height += $height_foot;

            //二维码
            $qr = self::getGoodsQr($user,$goods_info);
            $qr = get_whole_image($qr);
            $qr = imagecreatefrompng($qr);
            $width_qr = imagesx($qr);
            $height_qr = imagesx($qr);
            $width_qr_now = 200;
            $height_qr_now = $width_qr_now;

            //logo
            $logo = config("public_path").'/static/images/default_logo.png';
            $logo = imagecreatefrompng($logo);
            $width_logo = imagesx($logo);
            $height_logo = imagesy($logo);
            $width_logo_now = 60;
            $height_logo_now = $width_logo_now;

            // 创建画布
            $bg = imagecreatetruecolor($width, $height);
            $color = imagecolorallocatealpha($bg , 255 , 255 , 255 , 127);//白色
            imagefill($bg,0,0,$color);//填充画布

            //合并头部
            imagecopyresized($bg, $top, 0, 0, 0, 0,$width,$height_top, $width, $height_top);

            //填充白色
            $bg_white = imagecreatetruecolor($width, $height_white);
            $color_white = imagecolorAllocate($bg_white , 255 , 255 , 255);//白色
            imagefill($bg_white,0,0,$color_white);//填充画布
            imagecopyresized($bg, $bg_white, 0, $height_top, 0, 0,$width,$height_white, $width, $height_white);

            $xone = intval(($width-$width_font)/2);

            if($catch_news_img){
                //快讯若有图片合并
                imagecopyresized($bg, $newsImg, $xone, $height_news_y, 0, 0,$width_news_now, $height_news_now, $width_news,$height_news);
                if(!empty($addtext)){
                    $left = config("public_path").'/goodsleft.png';
                    $left = imagecreatefrompng($left);
                    $width_left = imagesx($left);
                    $white = imagecolorallocate($left, 255, 255, 255); // 创建黑色字体
                    imagettftext($left, 13, 45, 9, 83, $white, $font, $addtext);
                    imagecopyresized($bg, $left, $xone, $height_news_y, 0, 0,$width_news_now, $width_news_now, $width_left,$width_left);
                }
            }

            //合并底部
            imagecopyresized($bg, $foot, 0, $height_foot_y, 0, 0,$width_foot,$height_foot, $width_foot, $height_foot);

            //底部贴上二维码
            imagecopyresized($bg, $qr, $xone, $height_foot_y+$xone, 0, 0,$width_qr_now, $height_qr_now, $width_qr,$height_qr);

            //底部贴上logo
            imagecopyresized($bg, $logo, $xone+(($width_qr_now-$width_logo_now)/2), $height_foot_y+$xone+(($width_qr_now-$width_logo_now)/2), 0, 0,$width_logo_now, $height_logo_now, $width_logo,$height_logo);

            //填充文字内容
            $black = imagecolorallocate($bg, 0, 0, 0); // 创建黑色字体
            $red = imagecolorallocate($bg, 255, 0, 0); // 创建黑色字体
            imagettftext($bg, $font_size, 0, $xone, $height_top+$font_size+10, $black, $font, $text);
            imagettftext($bg, $font_size, 0, $xone*2+$width_qr_now, $height_foot_y+$font_size+$xone+40*1, $red, $font, "￥ ".$goods_info['price']);
            imagettftext($bg, 20, 0, $xone*2+$width_qr_now, $height_foot_y+$font_size+$xone+40*2, $black, $font, "购买赚：".$zijizhuan);
            if(!empty($jiazhuan)){
                imagettftext($bg, 20, 0, $xone*2+$width_qr_now, $height_foot_y+$font_size+$xone+40*3, $black, $font, "+分红赚：".$jiazhuan);
            }
            //填充发布时间
            $gray = imagecolorallocate($bg, 161, 161, 161); // 创建灰色字体
            imagettftext($bg, 24, 0, 100, $height_top-26, $gray, $font, $news_time);

            $finWidth = imagesx($bg);
            $finHeight = imagesy($bg);
            $percent = '0.8';
            //压缩

            $newbg = imagecreatetruecolor($finWidth*$percent, $finHeight*$percent);
            $colornew = imagecolorallocatealpha($bg , 255 , 255 , 255 , 127);//白色
            imagefill($newbg,0,0,$colornew);//填充画布

            imagecopyresampled($newbg,$bg,0,0,0,0,$finWidth*$percent,$finHeight*$percent,$finWidth,$finHeight);

            imagedestroy($bg);

            imagepng($newbg,$fullName);

            imagedestroy($newbg);
        }
        return get_whole_image(config("poster_path").'/newsPoster/'.$fileName);
    }

    /**
     * 体验店付款码
     * @param $store_info 体验店
     * @return string
     * @throws ServerException
     */
    static public function storeCode($store_info)
    {
        set_time_limit(0);
        @ini_set('memory_limit', '256M');
        mb_internal_encoding("UTF-8"); // 设置编码

        $type = 7;//当前第几次换样式  换一次加一 防止缓存
        $fullPath = config("public_path") . '/' . config("poster_path").'/newsPoster';
        //创建路径
        self::createDir($fullPath);

        $fileName = md5('u'.$store_info['business_id'].'s'.$store_info['id'].$type).'.png';
        $fullName = $fullPath.'/'.$fileName;
        if (!is_file($fullName))
        {
            $top = config("public_path").'/storeback.png';
            $top = imagecreatefrompng($top);

            $width = imagesx($top);
            $height = imagesy($top);//画布高度
            $height_top = imagesy($top);

            //二维码
            $qr = Poster::getQR($store_info);
            $qr = get_whole_image($qr);
            $qr = imagecreatefrompng($qr);
            $width_qr = imagesx($qr);
            $height_qr = imagesx($qr);
            $width_qr_now = 300;
            $height_qr_now = $width_qr_now;

            // 创建画布
            $bg = imagecreatetruecolor($width, $height);
            $color = imagecolorallocatealpha($bg , 255 , 255 , 255 , 127);//白色
            imagefill($bg,0,0,$color);//填充画布

            //合并头部
            imagecopyresized($bg, $top, 0, 0, 0, 0,$width,$height_top, $width, $height_top);

            $avg=($width-$width_qr_now)/2;
            //底部贴上二维码
            imagecopyresized($bg, $qr, $avg, $height_qr_now*1.5, 0, 0,$width_qr_now, $height_qr_now, $width_qr,$height_qr);

            $finWidth = imagesx($bg);
            $finHeight = imagesy($bg);
            $percent = '0.7';
            //压缩

            $newbg = imagecreatetruecolor($finWidth*$percent, $finHeight*$percent);
            $colornew = imagecolorallocatealpha($bg , 255 , 255 , 255 , 127);//白色
            imagefill($newbg,0,0,$colornew);//填充画布

            imagecopyresampled($newbg,$bg,0,0,0,0,$finWidth*$percent,$finHeight*$percent,$finWidth,$finHeight);

            imagedestroy($bg);

            imagepng($newbg,$fullName);

            imagedestroy($newbg);
        }
        return get_whole_image(config("poster_path").'/newsPoster/'.$fileName);
    }
    /**
     * 创建文件层级
     *
     * @param string $path 路径
     * @throws ServerException
     */
    static private function createDir($path)
    {
        //如果路径存在，则不做任何处理
        if (is_dir($path))
        {
            return;
        }
        else
        {
            //第三个参数是“true”表示能创建多级目录
            $result = mkdir($path, 0777, true);

            //创建目录失败
            if (!$result)
            {
                throw new ServerException('目录创建失败');
            }
        }

    }

    /**
     * 将纯文本换行
     * @param $fontsize 字体大小
     * @param $angle 角度
     * @param $fontface 字体名称
     * @param $string 字符串
     * @param $width 预设宽度
     * @return array 换行后的文本 和 换行次数
     */
    static public function autowrap($fontsize, $angle, $fontface, $string, $width) {

        $string = remove_all_tags($string);

        $content = "";

        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<mb_strlen($string);$i++) {
            $letter[] = mb_substr($string, $i, 1);
        }

        $num = 0;

        foreach ($letter as $l) {

            $teststr = $content." ".$l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);

            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $num++;
                $content .= "\n";
            }

            $content .= $l;
        }

        return [
            'content'=>$content,
            'num'=>$num
        ];
    }

    /**
     * 生成会员邀请码
     * @param $user
     * @return string
     * @throws ServerException
     */
    static public function getUserQr($user){
        Loader::import("phpqrcode.qrlib");
        $data = get_regis_url($user);
        //保存路径
        $savePath = config("public_path") . '/' . config("qrcode_path");
        //创建路径
        self::createDir($savePath);

        $guige = 'H';//可被覆盖范围 最大

        //文件名
        $fileName = 'u'.$user['id'].$guige.".png";
        //完整名称
        $fullName = $savePath . '/' .$fileName;
        if(!file_exists($fullName)){
            try
            {
                \QRcode::png($data, $fullName, $guige, 30, 2);
            }
            catch (Exception $exception)
            {
                throw new ServerException($exception->getMessage());
            }
        }
        return config("qrcode_path") . '/' .$fileName;
    }

    /**
     * 生成商品邀请码
     * @param $user
     * @param $goodsinfo
     * @return string
     * @throws ServerException
     */
    static public function getGoodsQr($user,$goodsinfo){
        Loader::import("phpqrcode.qrlib");
        $data = get_goods_url($user['mobile'],$goodsinfo['id']);
        //保存路径
        $savePath = config("public_path") . '/' . config("qrcode_path");
        //创建路径
        self::createDir($savePath);

        $guige = 'H';//可被覆盖范围 最大

        //文件名
        $fileName = 'g'.$goodsinfo['id'].'u'.$user['id'].$guige.".png";
        //完整名称
        $fullName = $savePath . '/' .$fileName;
        if(!file_exists($fullName)){
            try
            {
                \QRcode::png($data, $fullName, $guige, 30, 2);
            }
            catch (Exception $exception)
            {
                throw new ServerException($exception->getMessage());
            }
        }
        return config("qrcode_path") . '/' .$fileName;
    }


}
